package cn.lj.dao.impl;

import cn.lj.dao.AccountDao;
import cn.lj.domain.Account;
import cn.lj.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author lj
 * @Description:
 * @date 2020-12-02 13:30
 * @QQ 851477108
 */

public class AccountDaoImpl implements AccountDao {

    private QueryRunner runner;
    private ConnectionUtils connectionUtils;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            String sql = "select * from account";
            return runner.query(connectionUtils.getThreadConnection(),sql,new BeanListHandler<>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            String sql = "select * from account where id = #{id}";
            return runner.query(connectionUtils.getThreadConnection(),sql,new BeanHandler<>(Account.class),accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try {
            String sql = "insert into account (name,money) values (name=#{name},money=#{money})";
            runner.update(connectionUtils.getThreadConnection(),sql,account.getName(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            String sql = "update account set name=#{name}, money=#{money} where id=#{id}";
            runner.update(connectionUtils.getThreadConnection(),sql,account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            String sql = "delete from account where id=#{id}";
            runner.update(connectionUtils.getThreadConnection(),sql,accountId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountByName(String accountName) {
        try {
            String sql = "select * from account where name = #{name}";
            return runner.query(connectionUtils.getThreadConnection(),sql,new BeanHandler<>(Account.class),accountName);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
